package handler

import (
	"litetalk/api/form"
	"litetalk/proto"
	"litetalk/tools"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	var form form.FormLogin
	if err := c.ShouldBindJSON(&form); err != nil {
		FailWithMsg(c, "param:"+err.Error())
		return
	}

	req := &proto.IMLoginReq{
		UserName: form.UserName,
		Password: tools.Sha1(form.Password),
	}
	rep := &proto.IMLoginRes{}
	if err := logicRpc.Login(req, rep); err != nil {
		FailWithMsg(c, err.Error())
		return
	}
	if rep.Code == proto.CodeFailed || rep.AuthToken == "" {
		FailWithMsg(c, "")
	}

	SuccessWithMsg(c, "login success", rep)
}

func Register(c *gin.Context) {
	req := &proto.IMRegister{}
	if err := c.ShouldBindJSON(req); err != nil {
		FailWithMsg(c, err.Error())
		return
	}

	rep := &proto.IMRegisterAck{}
	if err := logicRpc.Register(req, rep); err != nil {
		FailWithMsg(c, err.Error())
		return
	}
	SuccessWithMsg(c, "regiester success", rep)
}

func Logout(c *gin.Context) {
	args := &proto.IMLogout{}
	if err := c.ShouldBindJSON(&args); err != nil {
		FailWithMsg(c, err.Error())
		return
	}
	reply := &proto.IMLogoutReply{}

	if err := logicRpc.Logout(args, reply); err != nil {
		FailWithMsg(c, "logout fail!")
		return
	}
	SuccessWithMsg(c, "logout ok!", nil)
}

func UpdatePassword(c *gin.Context) {
	args := &proto.IMChangePassword{}
	if err := c.ShouldBindJSON(args); err != nil {
		FailWithMsg(c, err.Error())
		return
	}

	reply := &proto.SuccessReply{}
	if err := logicRpc.ChangePassword(args, reply); err != nil {
		FailWithMsg(c, err.Error())
		return
	}
	SuccessWithMsg(c, "success", reply)
}

func DeleteUser(c *gin.Context) {
	args := &proto.IMDeleteUser{}
	if err := c.ShouldBindJSON(args); err != nil {
		FailWithMsg(c, err.Error())
		return
	}

	reply := &proto.SuccessReply{}
	if err := logicRpc.DeleteUser(args, reply); err != nil {
		FailWithMsg(c, err.Error())
		return
	}
	SuccessWithMsg(c, "success", reply)
}
